<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <el-form inline class="form">
        <el-form-item label="用户名：">
          <el-input placeholder="请输入用户名" v-model="userName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query()" :disabled="!userName">
            查询
          </el-button>
          <el-button type="primary" @click="resetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="openDrawer">添加用户</el-button>
      <el-button type="primary">批量删除</el-button>
      <el-table style="margin: 10px 0" border :data="userList">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="#" width="40" type="index"></el-table-column>
        <el-table-column label="用户id" prop="id"></el-table-column>
        <el-table-column label="用户名字" prop="name"></el-table-column>
        <el-table-column label="用户名称" prop="username"></el-table-column>
        <el-table-column label="用户角色" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="user"
              size="small"
              @click="openRoleDrawer(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              icon="edit"
              title="编辑"
              size="small"
              @click="edit(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定删除${row.username}吗？`"
              width="210"
              @confirm="deleteUser(row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="delete"
                  title="删除"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 12]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout=" prev, pager, next, jumper, ->,sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-drawer v-model="drawerFlag">
        <template #header>
          <h4>
            {{ userData.id ? '编辑用户' : '添加用户' }}
          </h4>
        </template>
        <template #default>
          <div>
            <el-form
              ref="userFormRef"
              label-position="right"
              label-width="100"
              :model="userData"
              :rules="rules"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userData.username"></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" prop="name">
                <el-input v-model="userData.name"></el-input>
              </el-form-item>
              <el-form-item
                label="用户密码"
                v-show="!userData.id"
                prop="password"
              >
                <el-input v-model="userData.password"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">保存</el-button>
          </div>
        </template>
      </el-drawer>

      <el-drawer v-model="roleDrawerFlag">
        <template #header>
          <h4>分配角色</h4>
        </template>
        <template #default>
          <div>
            <el-form ref="userFormRef" label-position="right" label-width="100">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userData.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="分配角色" prop="roleId">
                <el-checkbox
                  v-model="checkAll"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                >
                  全选
                </el-checkbox>
                <el-checkbox-group
                  v-model="checkedRole"
                  @change="handleCheckedRoleChange"
                >
                  <el-checkbox
                    v-for="role in roleList"
                    :key="role.id"
                    :label="role"
                    :value="role"
                  >
                    {{ role.roleName }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="roleCancelClick">取消</el-button>
            <el-button type="primary" @click="roleConfirmClick">保存</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="index">
import { onMounted, ref, nextTick } from 'vue'
import {
  reqUserList,
  reqAddUser,
  reqUpdateUser,
  reqDeleteUser,
  reqUserRoleList,
  reqAssignRole,
} from '@/api/acl/user'
import type { UserData, RoleData } from '@/api/acl/user/type.ts'
import { ElMessage } from 'element-plus'
import useLayoutStore from '@/store/modules/setting.ts'
const layoutStore = useLayoutStore()
const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)
const size = ref('small')
const disabled = ref(false)
const background = ref(true)

const userName = ref('')
const query = () => {
  getUserList()
}
const resetQuery = () => {
  layoutStore.refresh = !layoutStore.refresh
}
const userList = ref<UserData[]>([])

//
const drawerFlag = ref(false)

const userData = ref<UserData>({
  username: '',
  password: '',
  name: '',
  id: '',
})
const handleSizeChange = (val: number) => {
  console.log(`每页 ${val} 条`)
  getUserList()
}
const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`)
  getUserList(val)
}
const getUserList = async (page: number = 1) => {
  currentPage.value = page
  let res = await reqUserList(currentPage.value, pageSize.value, userName.value)
  if (res.code === 200) {
    console.log('获取用户列表成功', res.data)
    userList.value = res.data.records
    total.value = res.data.total
  }
}
onMounted(() => {
  getUserList()
})
const openDrawer = () => {
  console.log('add')
  userData.value = {
    username: '',
    password: '',
    name: '',
    id: '',
  }
  drawerFlag.value = true
  userFormRef.value?.clearValidate()
}
//编辑
const edit = (row: UserData) => {
  console.log('edit', row)
  userData.value = row
  drawerFlag.value = true
  nextTick(() => {
    //清除表单的校验信息
    userFormRef.value.clearValidate()
  })
}
//取消
const cancelClick = () => {
  drawerFlag.value = false
}
const validateName = (_rule: any, value: any, callback: any) => {
  if (value.trim() === '') {
    callback(new Error('用户昵称不能为空'))
  } else {
    if (value.trim().length < 3) {
      callback(new Error('用户昵称不能少于3个字符'))
    }
    callback()
  }
}
const validatePassword = (_rule: any, value: any, callback: any) => {
  if (userData.value.id) {
    //更新不校验密码
    callback()
  } else {
    if (value.trim() === '') {
      callback(new Error('用户密码不能为空'))
    } else {
      if (value.trim().length < 3) {
        callback(new Error('用户密码不能少于3个字符'))
      }
      callback()
    }
  }
}
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' },
  ],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  name: [{ required: true, trigger: 'blur', validator: validateName }],
})
const userFormRef = ref<any>()
//保存
const confirmClick = async () => {
  // 验证表单
  await userFormRef.value.validate()
  if (userData.value.id) {
    let res = await reqUpdateUser(userData.value)
    console.log('更新用户成功', res)
    if (res.code === 200) {
      ElMessage.success('更新用户成功')
      // 刷新页面 //用户修改当前登录账号 用户名信息
      window.location.reload()
    } else {
      ElMessage.error('更新用户失败')
    }
    drawerFlag.value = false
  } else {
    let res = await reqAddUser(userData.value)
    console.log('添加用户成功', res)
    if (res.code === 200) {
      ElMessage.success('添加用户成功')
    } else {
      ElMessage.error('添加用户失败')
    }
    drawerFlag.value = false
    getUserList()
  }
}
//删除
const deleteUser = async (id: number) => {
  console.log('delete', id)
  let res = await reqDeleteUser(id)
  if (res.code === 200) {
    ElMessage.success('删除用户成功')
    getUserList()
  } else {
    ElMessage.error('删除用户失败')
  }
}
//分配角色
//当前用户已分配角色
const checkedRole = ref<RoleData[]>([])
//全部角色
const roleList = ref<RoleData[]>([])
const checkAll = ref(false)
//属性用以表示 checkbox 的不确定状态
const isIndeterminate = ref(true)
const roleDrawerFlag = ref(false)
const openRoleDrawer = async (row: UserData) => {
  console.log('分配角色', row)
  roleDrawerFlag.value = true
  userData.value = row
  const res = await reqUserRoleList(row.id as number)
  if (res.code === 200) {
    console.log('获取角色列表成功', res.data)
    //全部角色
    roleList.value = res.data.allRolesList
    //当前用户已分配角色
    checkedRole.value = res.data.assignRoles
  }
}
const roleCancelClick = () => {
  roleDrawerFlag.value = false
}
const roleConfirmClick = async () => {
  console.log('checkedRole', checkedRole.value)
  let data = {
    userId: userData.value.id,
    roleIdList: checkedRole.value.map((role) => role.id),
  }
  let res = await reqAssignRole(data)
  if (res.code === 200) {
    ElMessage.success('分配角色成功')
    roleDrawerFlag.value = false
  } else {
    ElMessage.error('分配角色失败')
  }
}

const handleCheckAllChange = (val: any) => {
  //val为true时，全选，为false时取消全选
  console.log('checkAll', val)
  checkedRole.value = val ? roleList.value : []
  isIndeterminate.value = false
}
const handleCheckedRoleChange = (val: any) => {
  console.log('checkedRole', val)
  checkedRole.value = val
  checkAll.value = val.length === roleList.value.length
  isIndeterminate.value = val.length > 0 && val.length < roleList.value.length
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
